import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:image_picker/image_picker.dart';

class AddUpdateSonMaterialDialog extends StatefulWidget {
  final String baseApi;
  final int orderId;
  final String type;
  final Map item;
  final onSubmit;
  final Map numForm;

  AddUpdateSonMaterialDialog(
      {Key key,
      this.baseApi = 'EnterMaterialSon/',
      this.orderId,
      this.type,
      this.item,
      this.onSubmit,
      this.numForm})
      : super(key: key);

  @override
  State<StatefulWidget> createState() => AddUpdateSonMaterialDialogState();
}

class AddUpdateSonMaterialDialogState
    extends State<AddUpdateSonMaterialDialog> {
  int materialTypeId;
  String materialTypeName;
  List uploadList = [];
  List locatUploadList = [];
  String validDate = '';
  String baseApi = 'EnterMaterialSon/';
  String uploadVideoPath = '';
  String depName;

  final picker = ImagePicker();
  TextEditingController _nameController = new TextEditingController();
  TextEditingController _numController = new TextEditingController();
  TextEditingController _typesController = new TextEditingController();
  TextEditingController _unitController = new TextEditingController();
  TextEditingController _remarkController = new TextEditingController();
  TextEditingController _sonNumController = new TextEditingController();

  var eventBus = new EventBus();

  @override
  void initState() {
    super.initState();
    setState(() {
      baseApi = widget.baseApi;
    });
    initEditData();
    // 监听物资分类选择
    eventBus.on("enter_mct", (parmas) {
      var p = parmas['select'];
      setState(() {
        materialTypeId = p['id'];
        materialTypeName = p['name'];
      });
    });
  }

  initEditData() {
    print(widget.item);

    if (widget.type == 'edit' || widget.type == 'add') {
      List images = [];

      for (var item in widget.item['goods_imgs']) {
        images.add({'path': item, 'success': true});
      }

      var typeName = 'mtype';

      // if(widget.baseApi == 'EnterMaterialSon/') {
      //   typeName = 'mtypes';
      // }

      setState(() {
        materialTypeId = widget.item[typeName] != null
            ? widget.item[typeName]['goods_type_id']
            : null;
        materialTypeName = widget.item[typeName] != null
            ? widget.item[typeName]['type_name']
            : '请选择物资类型';
        uploadList = images;
        uploadVideoPath = widget.item['goods_video'] == null
            ? ''
            : widget.item['goods_video'];
      });

      _nameController.text = widget.item['name'];
      _numController.text = widget.item['num'].toString();
      _typesController.text = widget.item['specification'];
      _unitController.text = widget.item['unit'];
      _remarkController.text = widget.item['remark'];
      validDate = widget.item['valid_time'];
    }
  }

  // 添加物资
  _addMaterial() {
    var sonNum = _sonNumController.text.trim();

    if (sonNum.isEmpty) {
      Utils.showText(text: '请输入子物资数量', align: Alignment(0, 0));
      return;
    }

    if (double.tryParse(sonNum) == null) {
      Utils.showText(text: '请输入数字', align: Alignment(0, 0));
      return;
    }

    if (double.parse(sonNum) > widget.numForm['d_num']) {
      Utils.showText(text: '子物资数量大于子物资数量', align: Alignment(0, 0));
      return;
    }

    DioUtils.request("${baseApi}save",
        context: context,
        method: "POST",
        params: {
          'enter_material_id': widget.item['id'],
          'son_num': sonNum,
          'num': 1
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'id': ''});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  // 编辑物资
  _editMaterial() {
    int id = widget.item['id'];
    var name = _nameController.text.trim();
    var typeId = materialTypeId;
    var num = _numController.text.trim();
    var types = _typesController.text.trim();
    var unit = _unitController.text.trim();
    var remark = _remarkController.text.trim();

    if (name.isEmpty) {
      Utils.showText(text: '请输入物资名称', align: Alignment(0, 0));
      return;
    }
    if (typeId == null) {
      Utils.showText(text: '请选择物资类型', align: Alignment(0, 0));
      return;
    }
    if (num.toString().isEmpty) {
      Utils.showText(text: '请输入物资数量', align: Alignment(0, 0));
      return;
    }

    List images = [];

    for (var item in uploadList) {
      images.add(item['path']);
    }

    DioUtils.request("${baseApi}updMaterial",
        context: context,
        method: "POST",
        params: {
          'id': id,
          'name': name,
          'type_id': typeId,
          'num': num,
          'specification': types,
          'unit': unit,
          'remark': remark,
          'goods_imgs': images,
          'valid_time': validDate,
          'goods_video': uploadVideoPath,
        }, onSuccess: (res) {
      Utils.showText(text: res['msg']);
      if (res['code'] == 1) {
        widget.onSubmit({'id': ''});
        Navigator.pop(context);
      }
    }, onError: (error) {});
  }

  Widget _buildDialogHead(title) {
    return Container(
      height: 80.w,
      decoration: BoxDecoration(
          color: Utils.hexToColor('#F7F7F7'),
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(12.w), topRight: Radius.circular(12.w))),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: 31.w),
            child: Text(title,
                style: TextStyle(
                    color: Utils.hexToColor('#333333'),
                    fontSize: 16,
                    fontWeight: FontWeight.bold)),
          ),
          InkWell(
            onTap: () {
              Navigator.of(context).pop();
            },
            child: Container(
              padding: EdgeInsets.fromLTRB(30.w, 24.w, 30.w, 24.w),
              alignment: Alignment.topRight,
              child: Image.asset(
                'assets/dialog_close.png',
                width: 36.w,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildInput(title, controller, isEnable,
      [isNumber = false, maxLines = 1]) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 160.w,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              // textAlign: TextAlign.end,
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          Container(
            width: 460.w,
            height: maxLines > 1 ? 200.h : 70.h,
            child: TextField(
              enabled: isEnable,
              inputFormatters: [
                FilteringTextInputFormatter.allow(
                    RegExp(isNumber ? '[0-9]' : '[^]')),
              ],
              maxLines: maxLines,
              controller: controller,
              style: TextStyle(fontSize: 14, color: Colors.black), //输入文本的样式
              decoration: InputDecoration(
                hintText: '暂无',
                hintStyle: TextStyle(color: Color(0xFFC8C8D9), fontSize: 14),
                contentPadding: EdgeInsets.fromLTRB(21.w, 10, 21.w, 10),
                fillColor: Colors.white,
                filled: true,
                enabledBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Utils.hexToColor('#D4D4D4'),
                    width: 1,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(8.w),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSelectInput(title, value) {
    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Container(
            width: 160.w,
            height: 40,
            alignment: Alignment.centerRight,
            child: Text(
              title + '：',
              style:
                  TextStyle(color: Utils.hexToColor('#999999'), fontSize: 14),
            ),
          ),
          GestureDetector(
            onTap: () {
              // Navigator.pushNamed(context, "/material_type", arguments: {'baseApi': widget.baseApi});
            },
            child: Container(
              width: 460.w,
              height: 40,
              alignment: Alignment.centerLeft,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              // decoration: BoxDecoration(
              //   borderRadius: BorderRadius.circular(4),
              //   border: Border.all(color: Utils.hexToColor('#D2D2D2'), width: 1)
              // ),
              child: Container(
                child: Text(value.toString(),
                    style: TextStyle(
                        color: Utils.hexToColor(
                            (materialTypeName == '请选择物资类型' ||
                                    materialTypeName == null)
                                ? '#CBCACF'
                                : '#0000000'),
                        fontSize: 14)),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return Container(
        width: 700.w,
        height: 980.w,
        decoration:
            BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(100))),
        child: Column(
          children: <Widget>[
            _buildDialogHead('物资信息'),
            Expanded(
              flex: 1,
              child: SingleChildScrollView(
                child: Container(
                    padding: EdgeInsets.all(40.w),
                    child: Column(
                      children: <Widget>[
                        _buildInput('物资名称', _nameController, false),
                        _buildSelectInput('物资类型',
                            materialTypeName == null ? '暂无' : materialTypeName),
                        _buildInput('物资数量', _numController, false, true),
                        _buildInput('规格/型号', _typesController, false),
                        _buildInput('计量单位', _unitController, false),
                        _buildInput('备注', _remarkController, false, false),
                        _buildInput('子物资数量', _sonNumController, true, false),
                      ],
                    )),
              ),
            ),
            Container(
              height: 120.w,
              // color: Utils.hexToColor('#FFFFFF'),
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  border: Border(
                      top: BorderSide(
                          width: 1, color: Utils.hexToColor('#F2F2F2')))),
              child: SizedBox(
                width: 620.w,
                height: 76.w,
                child: ElevatedButton(
                  onPressed: () {
                    if (widget.type == 'add') {
                      _addMaterial();
                    }
                    if (widget.type == 'edit') {
                      _editMaterial();
                    }
                  },
                  child: Text(
                    '保存',
                    style: TextStyle(color: Colors.white),
                  ),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF297CFF),
                    shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.all(Radius.circular(60.w))),
                  ),
                ),
              ),
            )
          ],
        ));
  }
}
